package com.khyr.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.Vo.GetCheckOrderDetailsByItemIdVo;
import com.khyr.Vo.SearchSalesListCountVo;
import com.khyr.Vo.SearchSalesListVo;
import com.khyr.Vo.SelectSysCheckItemVo;
import com.khyr.dao.CareOrderDao;
import com.khyr.dao.CareOrderItemDao;
import com.khyr.dao.HisCheckResultDao;
import com.khyr.dao.SysCheckItemDao;
import com.khyr.entity.*;
import com.khyr.service.InspectionItemStatisticsService;
import com.khyr.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ：Zhang
 * @date ：Created in 2025/3/12 10:42
 * @description：检查项目统计
 * @modified By：
 * @version: 1.0
 */
@Service
public class InspectionItemStatisticsServiceImpl implements InspectionItemStatisticsService {
    @Autowired
    private CareOrderItemDao careOrderItemDao;
    @Autowired
    private CareOrderDao careOrderDao;
    @Autowired
    private SysCheckItemDao sysCheckItemDao;
    @Autowired
    private HisCheckResultDao hisCheckResultDao;
    /**
     * @create by: Zr
     * @description: 用于获取所有的检查项目
     * @create time: 2025/3/12 10:51
     * @param
     * @return com.khyr.vo.R<com.khyr.entity.SysCheckItem>
     */
    @Override
    public R<List<SysCheckItem>> selectSysCheckItem() {
        // 创建查询条件
        QueryWrapper<SysCheckItem> queryWrapper = new QueryWrapper<>();
        // 获取所有状态正常的检查项
        queryWrapper.eq("status","0");
        List<SysCheckItem> sysCheckItems = sysCheckItemDao.selectList(queryWrapper);
        if(sysCheckItems != null){
            return new R<>(200,"获取成功",sysCheckItems);
        }else{
            return new R<>(400,"获取失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 根据关键字模糊查询检查项
     * @create time: 2025/3/21 15:27
     * @param data
     * @return com.khyr.vo.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page<com.khyr.entity.SysCheckItem>>
     */
    @Override
    public R<Page<SysCheckItem>> selectSysCheckItemByKeyWords(SelectSysCheckItemVo data) {
        // 创建查询条件
        QueryWrapper<SysCheckItem> queryWrapper = new QueryWrapper<>();
        if(data.getKeywords() != null){
            queryWrapper.like("keywords",data.getKeywords());
        }
        // 获取所有状态正常的检查项
        queryWrapper.eq("status","0");
        // 开启分页
        if(data.getPageNum() != null && data.getPageSize() != null){
            Page<SysCheckItem> page = new Page<>(Integer.parseInt(data.getPageNum()), Integer.parseInt(data.getPageSize()));
            page = sysCheckItemDao.selectPage(page, queryWrapper);
            if(page != null){
                return new R<>(200,"获取成功",page);
            }else{
                return new R<>(400,"获取失败",null);
            }
        }else {
            return new R<>(400,"获取失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 通过检查项目名称，患者名，日期查询检查项目列表，若无输入日期则默认查询当天
     * @create time: 2025/3/12 14:23
     * @param data
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.HisCheckResult>>
     */
    @Override
    public R<List<HisCheckResult>> searchSalesList(SearchSalesListVo data) {
        QueryWrapper<HisCheckResult> queryWrapper = new QueryWrapper<>();
        // 患者名
        if(data.getPatientName() != null){
            queryWrapper.like("patient_name",data.getPatientName());
        }
        // 检查项目id
        if(data.getItemId() != null){
            queryWrapper.eq("check_item_id",data.getItemId());
        }
        if(data.getDateRange() != null){
            queryWrapper.between("create_time",data.getDateRange()[0],data.getDateRange()[1]);
        }else {
            queryWrapper.between("create_time", LocalDate.now(), LocalDate.now());
        }
        List<HisCheckResult> list = hisCheckResultDao.selectList(queryWrapper);
        if(list != null){
            return new R<>(200,"获取成功",list);
        }
        else{
            return new R<>(400,"获取失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 检查项目统计列表；通过检查项目名称日期查询检查项目列表，若无输入日期则默认查询当天
     * @create time: 2025/3/12 14:49
     * @param data
     * @return com.khyr.vo.R<java.util.List<com.khyr.Vo.SearchSalesListCountVo>>
     */
    @Override
    public R<List<SearchSalesListCountVo>> searchSalesListCount(SearchSalesListVo data) {
        QueryWrapper<HisCheckResult> queryWrapper = new QueryWrapper<>();
        // 检查项目名称
        if(data.getCheckItemId() != null){
            queryWrapper.eq("check_item_id",data.getCheckItemId());
        }
        // 日期
        if(data.getDateRange() != null){
            queryWrapper.between("create_time",data.getDateRange()[0],data.getDateRange()[1]);
        }else {
            queryWrapper.between("create_time", LocalDate.now(), LocalDate.now());
        }
        List<HisCheckResult> list = hisCheckResultDao.selectList(queryWrapper);
        // 聚合检查结果
        List<SearchSalesListCountVo> result = aggregateCheckResults(list);
        if (result != null){
            return new R<>(200,"获取成功",result);
        }else {
            return new R<>(400,"获取失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 查询该用户的处方及其详细信息，如果传入的处方类型（coType）为空，则查询检查处方
     * @create time: 2025/3/19 14:40
     * @param coType
     * @param patient
     * @return com.khyr.vo.R<java.util.List<com.khyr.entity.CareOrder>>
     */
    @Override
    public R<List<CareOrder>> getCareOrderListByCoType(String coType, HisPatient patient) {
        // 检查类型，如果传参则默认为查询检查处方信息
        if(coType==null){
            coType = "1";
        }
        // 创建查询条件
        QueryWrapper<CareOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("co_type",coType);
        queryWrapper.eq("patient_id",patient.getPatientId());
        List<CareOrder> careOrders = careOrderDao.selectList(queryWrapper);
        if(careOrders != null){
            // 遍历每个处方，查询对应的处方项
            for(CareOrder careOrder : careOrders){
                QueryWrapper<CareOrderItem> careOrderItemQueryWrapper = new QueryWrapper<>();
                careOrderItemQueryWrapper.eq("co_id",careOrder.getCoId());
                careOrder.setCareOrderItems(careOrderItemDao.selectList(careOrderItemQueryWrapper));
            }
            return new R<>(200,"获取成功",careOrders);
        }else {
            return new R<>(400,"获取失败",null);
        }
    }
    /**
     * @create by: Zr
     * @description: 根据开诊明细id(item_id) 查询处方明细(CareOrderItem)和检查结果(HisCheckResult)
     * @create time: 2025/3/19 15:11
     * @param itemId
     * @return com.khyr.vo.R<com.khyr.Vo.GetCheckOrderDetailsByItemIdVo>
     */
    @Override
    public R<GetCheckOrderDetailsByItemIdVo> getCheckOrderDetailsByItemId(String itemId) {
        QueryWrapper<HisCheckResult> queryWrapper = new QueryWrapper<>();
        // 查询检查结果
        queryWrapper.eq("coc_id",itemId);
        HisCheckResult checkResult = hisCheckResultDao.selectOne(queryWrapper);
        // 查询明细
        QueryWrapper<CareOrderItem> careOrderItemQueryWrapper = new QueryWrapper<>();
        careOrderItemQueryWrapper.eq("item_id",itemId);
        CareOrderItem careOrderItem = careOrderItemDao.selectOne(careOrderItemQueryWrapper);
        return new R<>(200,"获取成功",new GetCheckOrderDetailsByItemIdVo(careOrderItem,checkResult));
    }


    public List<SearchSalesListCountVo> aggregateCheckResults(List<HisCheckResult> list) {
        // 按 check_item_id 分组，并计算总金额和数量
        Map<Integer, SearchSalesListCountVo> resultMap = list.stream()
                .collect(Collectors.groupingBy(
                        HisCheckResult::getCheckItemId,
                        Collectors.collectingAndThen(
                                Collectors.toList(),
                                results -> {
                                    BigDecimal totalPrice = results.stream()
                                            .map(HisCheckResult::getPrice)
                                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                                    int count = results.size();
                                    HisCheckResult firstResult = results.get(0);
                                    return new SearchSalesListCountVo(
                                            firstResult.getCheckItemId(),
                                            firstResult.getCheckItemName(),
                                            totalPrice,
                                            count
                                    );
                                }
                        )
                ));

        // 将 Map 转换为 List
        return new ArrayList<>(resultMap.values());
    } 
}
